/**
 * Copyright 2016 JustWayward Team
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.ecy.quadratic.ui.presenter;

import android.content.Context;
import android.text.TextUtils;

import com.ecy.quadratic.api.ComicApi;
import com.ecy.quadratic.beans.BaseResponseBean;
import com.ecy.quadratic.beans.Community;
import com.ecy.quadratic.beans.CommunityListResponseBean;
import com.ecy.quadratic.beans.PageInfo;
import com.ecy.quadratic.beans.user.User;
import com.ecy.quadratic.manager.LikeManager;
import com.ecy.quadratic.manager.SettingManager;
import com.ecy.quadratic.reader.base.RxPresenter;
import com.ecy.quadratic.reader.utils.LogUtils;
import com.ecy.quadratic.reader.utils.RxUtil;
import com.ecy.quadratic.reader.utils.StringUtils;
import com.ecy.quadratic.ui.contract.LastCommunityContract;
import com.google.gson.Gson;

import java.util.ArrayList;

import javax.inject.Inject;

import rx.Observable;
import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * @author yuyh.
 * @date 2016/8/3.
 */
public class LastCommunityPresenter extends RxPresenter<LastCommunityContract.View>
        implements LastCommunityContract.Presenter<LastCommunityContract.View> {

    private Context mContext;
    private ComicApi comicApi;

    @Inject
    public LastCommunityPresenter(Context mContext, ComicApi comicApi) {
        this.mContext = mContext;
        this.comicApi = comicApi;
    }

    @Override
    public void refresh(String page) {
        String key = StringUtils.creatAcacheKey("lastcommunity-list", page, SettingManager.getInstance().getUserChooseSex());
        Observable<CommunityListResponseBean> fromNetWork = comicApi.getLastCommunityList(page)
                .compose(RxUtil.<CommunityListResponseBean>rxCacheBeanHelper(key));

        //依次检查disk、network
        Subscription rxSubscription = Observable.concat(RxUtil.rxCreateDiskObservable(key, CommunityListResponseBean.class), fromNetWork)

                .observeOn(AndroidSchedulers.mainThread())
                .map(new Func1<CommunityListResponseBean, CommunityListResponseBean>() {
                    @Override
                    public CommunityListResponseBean call(CommunityListResponseBean old) {
                        System.out.println("map:call");
                        if (old != null && old.getResult() != null && old.getResult().list != null) {
                            for (int i = 0; i < old.getResult().list.size(); i++) {
                                String userJson = old.getResult().list.get(i).user;
                                if (!TextUtils.isEmpty(userJson)) {
                                    try {
                                        User user = new Gson().fromJson(userJson, User.class);
                                        old.getResult().list.get(i).userBean = user;
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }

                                old.getResult().list.get(i).isLiked = LikeManager.getInstance().isCollected(old.getResult().list.get(i).id);

                                String tagsJson = old.getResult().list.get(i).tags;
                                try {
                                    if (!TextUtils.isEmpty(tagsJson)) {
                                        old.getResult().list.get(i).tagsBean = new Gson().fromJson(tagsJson, ArrayList.class);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                                String imgJson = old.getResult().list.get(i).imgs;
                                try {
                                    if (!TextUtils.isEmpty(imgJson)) {
                                        old.getResult().list.get(i).imagesBean = new Gson().fromJson(imgJson, ArrayList.class);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            }
                        }

                        return old;
                    }
                })
                .subscribe(new Observer<CommunityListResponseBean>() {
                    @Override
                    public void onNext(CommunityListResponseBean communityBean) {
                        if (communityBean != null) {
                            PageInfo<Community> list = communityBean.getResult();
                            if (list != null && mView != null) {
                                mView.showRefreshList(list);
                            }
                        }
                    }

                    @Override
                    public void onCompleted() {
                        mView.complete();
                    }

                    @Override
                    public void onError(Throwable e) {
                        LogUtils.e("getLastCommunityList", e.toString());
                        mView.showError();
                    }
                });
        addSubscrebe(rxSubscription);
    }

    @Override
    public void loadMore(String page) {
        String key = StringUtils.creatAcacheKey("lastcommunity-list", page, SettingManager.getInstance().getUserChooseSex());
        Observable<CommunityListResponseBean> fromNetWork = comicApi.getLastCommunityList(page)
                .compose(RxUtil.<CommunityListResponseBean>rxCacheBeanHelper(key));

        //依次检查disk、network
        Subscription rxSubscription = Observable.concat(RxUtil.rxCreateDiskObservable(key, CommunityListResponseBean.class), fromNetWork)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<CommunityListResponseBean>() {
                    @Override
                    public void onNext(CommunityListResponseBean recommend) {
                        if (recommend != null) {
                            PageInfo<Community> list = recommend.getResult();
                            if (list != null && mView != null) {
                                mView.showLoadMoreList(list);
                            }
                        }
                    }

                    @Override
                    public void onCompleted() {
                        mView.complete();
                    }

                    @Override
                    public void onError(Throwable e) {
                        LogUtils.e("getLastCommunityList", e.toString());
                        mView.showError();
                    }
                });
        addSubscrebe(rxSubscription);
    }

    @Override
    public void postLike(String communityId) {
        Observable<BaseResponseBean> fromNetWork = comicApi.postCommunityLike(communityId);


        //依次检查disk、network
        Subscription rxSubscription = fromNetWork.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseResponseBean>() {
                    @Override
                    public void onNext(BaseResponseBean communityBean) {
                        if (communityBean != null && communityBean.getStatus() == 100) {
                            mView.postLikeSuccessful();
                        }
                    }

                    @Override
                    public void onCompleted() {
                        mView.complete();
                    }

                    @Override
                    public void onError(Throwable e) {
                        LogUtils.e("getLastCommunityList", e.toString());
                        mView.showError();
                    }
                });
        addSubscrebe(rxSubscription);
    }
}
